package org.viva.core.util;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;
import org.viva.core.Log;

import freemarker.template.TemplateDirectiveModel;

public class FreemarkerTagUtils implements ApplicationContextAware {

	private ApplicationContext context;

	public Map<String, Object> exec() throws IOException {
		Map<String, Object> map = new HashMap<>();
		Resource[] res = UTIL.RES.getResources("classpath*:" + "org/viva/macro/**/*.class");
		String className;
		for (Resource r : res) {
			try {
				className = r.getURL().toString();
				className = className.split("(classes/)|(!/)")[1];
				className = className.replace("/", ".");
				className = className.replace(".class", "");
				Class<?> class1 = Class.forName(className);
				if (TemplateDirectiveModel.class.isAssignableFrom(class1)) {
					if (class1.isAnnotationPresent(Service.class)) {
						Service service = class1.getAnnotation(Service.class);
						map.put(service.value(), context.getBean(service.value()));
						System.out.println("load marco:" + service.value());
					}
				}
			} catch (Exception e) {
				Log.error(e.getMessage(), e);
			}
		}
		return map;
	}

	@Override
	public void setApplicationContext(ApplicationContext context) throws BeansException {
		this.context = context;
	}

}
